/**
 * EEPA接口一致性测试脚本
 * 测试daily-energy和activity-analysis接口的EEPA值一致性
 */

const API_BASE_URL = 'http://localhost:3000/api/health'

// 测试数据
const TEST_USER_ID = 68
const TEST_DATE = '2025-09-29'

/**
 * 测试daily-energy接口
 */
async function testDailyEnergyAPI() {
  console.log('\n=== 测试 daily-energy 接口 ===')
  
  try {
    const response = await fetch(`${API_BASE_URL}/daily-energy?userId=${TEST_USER_ID}&date=${TEST_DATE}`)
    const result = await response.json()
    
    console.log('响应状态:', response.status)
    if (result.success) {
      console.log('daily-energy 结果:')
      console.log(`  EEPA: ${result.data.eepa} kcal`)
      console.log(`  BMR: ${result.data.bmr} kcal`)
      console.log(`  TEF: ${result.data.tef} kcal`)
      console.log(`  TEE: ${result.data.tee} kcal`)
      
      console.log('\n  活动分解:')
      Object.entries(result.data.activity_breakdown).forEach(([activity, data]) => {
        console.log(`    ${activity}: ${data.duration_mins}分钟, ${data.calories.toFixed(1)} kcal, MET=${data.avg_met}`)
      })
      
      console.log('\n  日总结:')
      console.log(`    总活动时间: ${result.data.daily_summary.total_activity_mins}分钟`)
      console.log(`    平均心率: ${result.data.daily_summary.avg_heart_rate} bpm`)
      console.log(`    总步数: ${result.data.daily_summary.total_steps}`)
      console.log(`    活动卡路里: ${result.data.daily_summary.active_calories} kcal`)
      console.log(`    静息卡路里: ${result.data.daily_summary.rest_calories} kcal`)
      
      return {
        eepa: result.data.eepa,
        activityBreakdown: result.data.activity_breakdown,
        dailySummary: result.data.daily_summary
      }
    } else {
      console.log('daily-energy 失败:', result.error)
      return null
    }
    
  } catch (error) {
    console.error('测试daily-energy接口失败:', error)
    return null
  }
}

/**
 * 测试activity-analysis接口
 */
async function testActivityAnalysisAPI() {
  console.log('\n=== 测试 activity-analysis 接口 ===')
  
  try {
    // 构造正确的时间范围（与daily-energy保持一致）
    const startDate = `${TEST_DATE}T00:00:00.000Z`
    const endDate = `${TEST_DATE}T23:59:59.999Z`
    
    const response = await fetch(`${API_BASE_URL}/activity-analysis?userId=${TEST_USER_ID}&startDate=${startDate}&endDate=${endDate}`)
    const result = await response.json()
    
    console.log('响应状态:', response.status)
    if (result.success) {
      console.log('activity-analysis 结果:')
      console.log(`  总窗口数: ${result.data.total_windows}`)
      
      // 计算总EEPA和活动分解
      let totalEEPA = 0
      const activityBreakdown = {
        '睡眠行为': { duration_mins: 0, calories: 0 },
        '静息行为': { duration_mins: 0, calories: 0 },
        '低强度活动': { duration_mins: 0, calories: 0 },
        '中强度活动': { duration_mins: 0, calories: 0 },
        '高强度活动': { duration_mins: 0, calories: 0 }
      }
      
      let totalSteps = 0
      let totalHeartRateSum = 0
      let heartRateCount = 0
      
      result.data.analysis_results.forEach(window => {
        const classification = window.classification
        
        totalSteps += window.window_data.steps_sum
        totalHeartRateSum += window.window_data.hr_mean
        heartRateCount++
        
        if (classification.classification_type === 'single') {
          const activityType = classification.activity
          const calories = classification.calories
          
          activityBreakdown[activityType].duration_mins += 10
          activityBreakdown[activityType].calories += calories
          totalEEPA += calories
        } else if (classification.classification_type === 'composition') {
          const compositionMins = classification.composition_mins
          const totalCalories = classification.calories
          
          Object.entries(compositionMins).forEach(([activityType, duration]) => {
            if (duration > 0) {
              const proportionalCalories = (duration / 10) * totalCalories
              activityBreakdown[activityType].duration_mins += duration
              activityBreakdown[activityType].calories += proportionalCalories
            }
          })
          
          totalEEPA += totalCalories
        }
      })
      
      console.log(`  计算得出的EEPA: ${totalEEPA.toFixed(1)} kcal`)
      
      console.log('\n  活动分解:')
      Object.entries(activityBreakdown).forEach(([activity, data]) => {
        if (data.duration_mins > 0) {
          console.log(`    ${activity}: ${data.duration_mins}分钟, ${data.calories.toFixed(1)} kcal`)
        }
      })
      
      const avgHeartRate = heartRateCount > 0 ? Math.round(totalHeartRateSum / heartRateCount) : 0
      const activeCalories = activityBreakdown['低强度活动'].calories + 
                            activityBreakdown['中强度活动'].calories + 
                            activityBreakdown['高强度活动'].calories
      const restCalories = activityBreakdown['睡眠行为'].calories + 
                          activityBreakdown['静息行为'].calories
      
      console.log('\n  日总结:')
      console.log(`    总活动时间: ${Object.values(activityBreakdown).reduce((sum, activity) => sum + activity.duration_mins, 0)}分钟`)
      console.log(`    平均心率: ${avgHeartRate} bpm`)
      console.log(`    总步数: ${totalSteps}`)
      console.log(`    活动卡路里: ${activeCalories.toFixed(1)} kcal`)
      console.log(`    静息卡路里: ${restCalories.toFixed(1)} kcal`)
      
      return {
        eepa: totalEEPA,
        activityBreakdown,
        dailySummary: {
          total_activity_mins: Object.values(activityBreakdown).reduce((sum, activity) => sum + activity.duration_mins, 0),
          avg_heart_rate: avgHeartRate,
          total_steps: totalSteps,
          active_calories: activeCalories,
          rest_calories: restCalories
        }
      }
    } else {
      console.log('activity-analysis 失败:', result.error)
      return null
    }
    
  } catch (error) {
    console.error('测试activity-analysis接口失败:', error)
    return null
  }
}

/**
 * 对比两个接口的结果
 */
function compareResults(dailyEnergyResult, activityAnalysisResult) {
  console.log('\n=== 结果对比分析 ===')
  
  if (!dailyEnergyResult || !activityAnalysisResult) {
    console.log('❌ 无法进行对比，其中一个接口返回了错误')
    return
  }
  
  // EEPA对比
  const eepa1 = dailyEnergyResult.eepa
  const eepa2 = activityAnalysisResult.eepa
  const eepaDiff = Math.abs(eepa1 - eepa2)
  const eepaPercDiff = (eepaDiff / Math.max(eepa1, eepa2) * 100).toFixed(2)
  
  console.log(`EEPA对比:`)
  console.log(`  daily-energy: ${eepa1} kcal`)
  console.log(`  activity-analysis: ${eepa2.toFixed(1)} kcal`)
  console.log(`  差异: ${eepaDiff.toFixed(1)} kcal (${eepaPercDiff}%)`)
  
  if (eepaDiff < 1) {
    console.log('  ✅ EEPA值基本一致 (差异 < 1 kcal)')
  } else if (eepaDiff < 5) {
    console.log('  ⚠️ EEPA值略有差异 (差异 < 5 kcal)')
  } else {
    console.log('  ❌ EEPA值差异较大 (差异 >= 5 kcal)')
  }
  
  // 活动分解对比
  console.log('\n活动分解对比:')
  const activities = ['睡眠行为', '静息行为', '低强度活动', '中强度活动', '高强度活动']
  
  activities.forEach(activity => {
    const duration1 = dailyEnergyResult.activityBreakdown[activity]?.duration_mins || 0
    const duration2 = activityAnalysisResult.activityBreakdown[activity]?.duration_mins || 0
    const calories1 = dailyEnergyResult.activityBreakdown[activity]?.calories || 0
    const calories2 = activityAnalysisResult.activityBreakdown[activity]?.calories || 0
    
    const durationDiff = Math.abs(duration1 - duration2)
    const caloriesDiff = Math.abs(calories1 - calories2)
    
    console.log(`  ${activity}:`)
    console.log(`    时长: ${duration1}分钟 vs ${duration2}分钟 (差异: ${durationDiff}分钟)`)
    console.log(`    卡路里: ${calories1.toFixed(1)} vs ${calories2.toFixed(1)} (差异: ${caloriesDiff.toFixed(1)})`)
  })
  
  // 日总结对比
  console.log('\n日总结对比:')
  const summary1 = dailyEnergyResult.dailySummary
  const summary2 = activityAnalysisResult.dailySummary
  
  console.log(`  总步数: ${summary1.total_steps} vs ${summary2.total_steps} (差异: ${Math.abs(summary1.total_steps - summary2.total_steps)})`)
  console.log(`  平均心率: ${summary1.avg_heart_rate} vs ${summary2.avg_heart_rate} (差异: ${Math.abs(summary1.avg_heart_rate - summary2.avg_heart_rate)})`)
  console.log(`  活动卡路里: ${summary1.active_calories} vs ${summary2.active_calories.toFixed(1)} (差异: ${Math.abs(summary1.active_calories - summary2.active_calories).toFixed(1)})`)
  console.log(`  静息卡路里: ${summary1.rest_calories} vs ${summary2.rest_calories.toFixed(1)} (差异: ${Math.abs(summary1.rest_calories - summary2.rest_calories).toFixed(1)})`)
}

/**
 * 主测试函数
 */
async function main() {
  console.log('开始测试EEPA接口一致性...')
  console.log('测试用户ID:', TEST_USER_ID)
  console.log('测试日期:', TEST_DATE)
  console.log('目标：验证重构后的daily-energy接口与activity-analysis接口返回一致的EEPA值')
  
  // 1. 测试daily-energy接口
  const dailyEnergyResult = await testDailyEnergyAPI()
  
  // 2. 测试activity-analysis接口
  const activityAnalysisResult = await testActivityAnalysisAPI()
  
  // 3. 对比结果
  compareResults(dailyEnergyResult, activityAnalysisResult)
  
  console.log('\n测试完成!')
  console.log('\n💡 期望结果:')
  console.log('- EEPA值差异应该 < 1 kcal')
  console.log('- 活动分解应该基本一致')
  console.log('- 日总结数据应该相同')
  console.log('- 如果还有差异，可能需要进一步调整算法细节')
}

// 运行测试
if (require.main === module) {
  main().catch(console.error)
}

module.exports = {
  testDailyEnergyAPI,
  testActivityAnalysisAPI,
  compareResults
}
